#include "paddle.h"
#include "pingpong.h"

Paddle::Paddle(int x, int y, int width, int heigth, bool isLeftPaddle)
{
    this->setX(qreal(x));
    this->setY(qreal(y));
    this->width = width;
    this->heigth = heigth;
    this->speed= 15;
    this->canGoDown = true;
    this->canGoUp = true;
    this->isLeftPaddle = isLeftPaddle;
    this->calculateCCAngles();
}
Paddle::Paddle()
{
}
Paddle::~Paddle()
{
}
QRectF Paddle::boundingRect() const
{
    return QRectF(0, 0, width, heigth);
}
void Paddle::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
    painter->setBrush(QBrush(Qt::black, Qt::SolidPattern));
    painter->drawRect(0,0,width, heigth);
}
void Paddle::setSpeed(int newspeed)
{
    speed=newspeed;
}
QPainterPath Paddle::shape() const
{
    QPainterPath path;
    path.addRect(this->boundingRect());
    return path;
}
void Paddle::goUp()
{
    for(int i = 0; i < speed; ++i) {
        canGoDown = true;
        if(canGoUp) this->setPos(this->mapToParent(0,-1));
        checkWallCollisions(true);
    }
}
void Paddle::goDown()
{
   for(int i = 0; i <= speed; ++i) {
        canGoUp = true;
        if(canGoDown) this->setPos(this->mapToParent(0,1));
        checkWallCollisions(false);
   }
}
void Paddle::checkWallCollisions(bool goingUp)
{
    QList<QGraphicsItem *> sceneItems = scene()->items();
    foreach (QGraphicsItem *item, sceneItems)
    {
        if(item == this) continue;
        if(this->collidesWithItem(item))
        {
            if(item->type() == QGraphicsLineItem().type() || item->type() == Ball().type())
            {
                if(goingUp) {
                    canGoUp = false;
                }
                if(!goingUp) {
                    canGoDown = false;
                }
            }
        }
    }
}
bool Paddle::getIsLeftPaddle()
{
    return isLeftPaddle;
}
void Paddle::calculateCCAngles()
{
    double angleHax = 0.5;
    leftTopCCAngle = MathOperations::getAngleXYOrigin(this->boundingRect().topLeft(),this->boundingRect().center(), true)-0.5;
    rightTopCCAngle = MathOperations::getAngleXYOrigin(this->boundingRect().topRight(),this->boundingRect().center(), true)+0.5;
    leftBottomCCAngle = MathOperations::getAngleXYOrigin(this->boundingRect().bottomLeft(),this->boundingRect().center(), true)+0.5;
    rightBottomCCAngle = MathOperations::getAngleXYOrigin(this->boundingRect().bottomRight(),this->boundingRect().center(), true)-0.5;
    if(this->isLeftPaddle) {
            leftTopCCAngle -= angleHax;
            rightTopCCAngle += angleHax;
            leftBottomCCAngle += angleHax;
            rightBottomCCAngle -= angleHax;
    }
    else {
        leftTopCCAngle += angleHax;
        rightTopCCAngle -= angleHax;
        leftBottomCCAngle -= angleHax;
        rightBottomCCAngle += angleHax;
    }
}
